package com.fastloan.mgt.product.question.service.impl;

import com.alibaba.fastjson.JSON;
import com.fastloan.common.BasicServiceImpl;
import com.fastloan.mgt.product.label.service.LabelService;
import com.fastloan.mgt.product.question.dao.ProductQuestionMapper;
import com.fastloan.mgt.product.question.model.ProductQuestionOption;
import com.fastloan.mgt.product.question.model.vo.ProductQuestionVO;
import com.fastloan.mgt.product.question.service.ProductQuestionOptionService;
import com.fastloan.mgt.product.question.service.ProductQuestionService;
import com.fastloan.mgt.product.question.model.ProductQuestion;
import com.fastloan.safe.core.util.ManagerKit;
import com.kawins.supers.tree.Bean2TreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author admins
 * createTime 2017/12/27
 */
@Service
public class ProductQuestionServiceImpl extends BasicServiceImpl<ProductQuestion> implements ProductQuestionService {
    @Autowired
    private ProductQuestionMapper productQuestionMapper;

    @Autowired
    private ProductQuestionOptionService productQuestionOptionService;

    @Autowired
    private LabelService labelService;

    @Override
    @Transactional
    public void insertQuestion(ProductQuestion productQuestion, String questionOptionJson, String optionId) {
        ProductQuestionOption productQuestionOption = new ProductQuestionOption();
        if (!StringUtils.isBlank(optionId)) {
            productQuestionOption = verify(optionId);
        }
        getProductQuestionOption(productQuestion);
        productQuestion.setOrgId(ManagerKit.getOrgId());
        insertSelective(productQuestion);
        List<ProductQuestionOption> productQuestionOptionList = JSON.parseArray(questionOptionJson, ProductQuestionOption.class);
        ProductQuestionOption finalProductQuestionOption = productQuestionOption;
        productQuestionOptionList.forEach(questionOption -> {
            questionOption.setQuestionId(productQuestion.getId());
            productQuestionOptionService.insertSelective(questionOption);
            finalProductQuestionOption.setNextQuestionId(productQuestion.getId());
            productQuestionOptionService.updateByPrimaryKeySelective(finalProductQuestionOption);
        });
    }

    @Override
    @Transactional
    public void updateQuestion(ProductQuestion productQuestion, String questionOptionJson, String optionId) {
        ProductQuestionOption productQuestionOption = new ProductQuestionOption();
        //变更问题
        verifyQuestionInfo(productQuestion);
        if (!StringUtils.isBlank(optionId)) {
            productQuestionOption = verify(optionId);
            productQuestionOption.setNextQuestionId(productQuestion.getId());
            productQuestionOptionService.updateByPrimaryKeySelective(productQuestionOption);
        }
        updateByPrimaryKeySelective(productQuestion);

        //变更答案
        if (!StringUtils.isBlank(questionOptionJson)){
            List<ProductQuestionOption> productQuestionOptionList = JSON.parseArray(questionOptionJson, ProductQuestionOption.class);
            List<ProductQuestionOption> questionOptionList = productQuestionOptionService.select(productQuestionOption);
            if (questionOptionList.size() > productQuestionOptionList.size()) {
                questionOptionList.forEach(productQuestionOptionService::deleteByPrimaryKey);
            }
            productQuestionOptionList.forEach(productQuestionOptionService::insertSelective);
        }
    }

    @Override
    public List<ProductQuestionVO> queryQuestion() {
        Bean2TreeUtil<ProductQuestionVO> treeUtil = new Bean2TreeUtil<>();
        List<ProductQuestionVO> questionVOList
                = treeUtil.getChildNodesByParentId(productQuestionMapper.queryQuestion(ManagerKit.getOrgId()), 0);
        setQuestionVoInfo(questionVOList);
        return questionVOList;
    }

    @Override
    public ProductQuestionVO queryQuestionById(String questionId) {
        ProductQuestionVO questionVO = productQuestionMapper.queryQuestionById(questionId);
        accept(questionVO);
        return questionVO;
    }

    @Override
    public ProductQuestionVO queryBeginQuestion() {
        ProductQuestion question = new ProductQuestion();
        question.setOrgId(ManagerKit.getOrgId());
        question.setBeginQuestion(0);
        ProductQuestion productQuestion = selectOne(question);
        return queryQuestionById(productQuestion.getId());
    }

    private void accept(ProductQuestionVO questionVO) {
        List<ProductQuestionOption> productQuestionOptions
                = productQuestionOptionService.queryOptionByQuestionId(questionVO.getQuId());
        List<ProductQuestionOption> productQuestionOptionList = productQuestionOptions
                .stream()
                .peek(questionOption -> {
                    if (!StringUtils.isBlank(questionOption.getNextQuestionId())) {
                        questionOption.setIfBinding(true);
                    }
                })
                .collect(toList());
        questionVO.setProductQuestionOption(productQuestionOptionList);
        if (!StringUtils.isBlank(questionVO.getLabels())) {
            questionVO.setLabelList(labelService.queryByIdS(questionVO.getLabels()));
        }
    }

    private ProductQuestionOption verify(String optionId) {
        ProductQuestionOption productQuestionOption = productQuestionOptionService.selectByPrimaryKey(optionId);
        if (productQuestionOption == null) {
            throw new RuntimeException("请选择未绑定的答案");
        } else if (!StringUtils.isBlank(productQuestionOption.getNextQuestionId())) {
            throw new RuntimeException("此答案以绑定题目");
        }
        return productQuestionOption;
    }

    private void getProductQuestionOption(ProductQuestion productQuestion) {
        if (productQuestion.getBeginQuestion() != null && productQuestion.getBeginQuestion().equals(0)) {
            ProductQuestion question = new ProductQuestion();
            question.setOrgId(ManagerKit.getOrgId());
            question.setBeginQuestion(0);
            ProductQuestion temp = selectOne(question);
            if (temp != null) {
                throw new RuntimeException("已存在初始问题, 不能重复添加");
            }
        }
    }

    private void verifyQuestionInfo(ProductQuestion productQuestion) {
        if (productQuestion.getBeginQuestion() != null && productQuestion.getBeginQuestion().equals(0)) {
            ProductQuestion question = selectByPrimaryKey(productQuestion.getId());
            if (question.getBeginQuestion().equals(1)) {
                throw new RuntimeException("不能变更为初始题目");
            }
        }
    }

    private void setQuestionVoInfo(List<ProductQuestionVO> questionVOList) {
        if (questionVOList != null && !questionVOList.isEmpty()) {
            for (ProductQuestionVO questionVO : questionVOList) {
                accept(questionVO);
                if (!questionVO.getQuestionVOList().isEmpty()) {
                    setQuestionVoInfo(questionVO.getQuestionVOList());
                }
            }
        }
    }
}
